#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import os
import shutil
from datetime import datetime

class BangumiHTMLGenerator:
    """生成B站追番列表HTML页面"""
    
    def __init__(self, data_file='bangumi_data.json'):
        self.data_file = data_file
        self.output_dir = 'bangumi_page'
        self.html_file = os.path.join(self.output_dir, 'index.html')
        self.css_file = os.path.join(self.output_dir, 'css', 'style.css')
        self.js_file = os.path.join(self.output_dir, 'js', 'main.js')
        
    def load_data(self):
        """加载番剧数据"""
        try:
            with open(self.data_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            print(f"错误: 找不到数据文件 {self.data_file}")
            print("请先运行爬虫程序获取数据")
            return None
        except json.JSONDecodeError:
            print(f"错误: 数据文件 {self.data_file} 格式不正确")
            return None
    
    def create_directory_structure(self):
        """创建输出目录结构"""
        # 创建主目录
        os.makedirs(self.output_dir, exist_ok=True)
        
        # 创建CSS和JS目录
        os.makedirs(os.path.join(self.output_dir, 'css'), exist_ok=True)
        os.makedirs(os.path.join(self.output_dir, 'js'), exist_ok=True)
        os.makedirs(os.path.join(self.output_dir, 'images'), exist_ok=True)
        
        print(f"创建目录结构: {self.output_dir}")
    
    def generate_html(self, bangumi_data):
        """生成HTML页面"""
        if not bangumi_data:
            return False
        
        # 获取番剧列表和更新时间
        bangumi_list = bangumi_data['data']
        update_time = bangumi_data['update_time']
        total_count = bangumi_data['total']
        
        # 统计不同状态的番剧数量
        watching_count = len([b for b in bangumi_list if b['status'] == 'watching'])
        finished_count = len([b for b in bangumi_list if b['status'] == 'finished'])
        
        # 生成HTML内容
        html_content = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的B站追番列表</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>
<body>
    <header class="header">
        <div class="container">
            <div class="logo">
                <i class="fas fa-tv"></i>
                <h1>我的追番列表</h1>
            </div>
            <div class="search-box">
                <input type="text" id="search-input" placeholder="搜索番剧...">
                <button id="search-btn"><i class="fas fa-search"></i></button>
            </div>
        </div>
    </header>
    
    <div class="filter-container">
        <div class="container">
            <div class="filter-tabs">
                <button class="filter-btn active" data-filter="all">全部 <span class="count">{total_count}</span></button>
                <button class="filter-btn" data-filter="watching">追番中 <span class="count">{watching_count}</span></button>
                <button class="filter-btn" data-filter="finished">已看完 <span class="count">{finished_count}</span></button>
            </div>
            <div class="sort-options">
                <select id="sort-select">
                    <option value="default">默认排序</option>
                    <option value="title-asc">标题 (A-Z)</option>
                    <option value="title-desc">标题 (Z-A)</option>
                </select>
            </div>
        </div>
    </div>
    
    <main class="main-content">
        <div class="container">
            <div class="bangumi-grid" id="bangumi-container">
'''
        
        # 生成番剧卡片
        for bangumi in bangumi_list:
            status_class = bangumi['status']
            status_text = "追番中" if status_class == "watching" else "已看完"
            status_icon = "play-circle" if status_class == "watching" else "check-circle"
            
            html_content += f'''
                <div class="bangumi-card" data-status="{status_class}" data-title="{bangumi['title']}">
                    <div class="card-cover">
                        <img src="{bangumi['cover']}" alt="{bangumi['title']}">
                        <div class="status-badge {status_class}">
                            <i class="fas fa-{status_icon}"></i> {status_text}
                        </div>
                    </div>
                    <div class="card-info">
                        <h3 class="bangumi-title">{bangumi['title']}</h3>
                        <div class="bangumi-meta">
                            <span class="score"><i class="fas fa-star"></i> {bangumi['score']}</span>
                            <span class="progress"><i class="fas fa-list-ol"></i> {bangumi['progress']}</span>
                        </div>
                    </div>
                    <div class="card-hover">
                        <div class="bangumi-desc">{bangumi['evaluate'][:100]}...</div>
                        <a href="{bangumi['url']}" target="_blank" class="watch-btn">
                            <i class="fas fa-play-circle"></i> 观看
                        </a>
                    </div>
                </div>'''
        
        # 完成HTML内容
        html_content += '''
            </div>
            
            <div class="no-results" style="display: none;">
                <i class="fas fa-search"></i>
                <p>没有找到匹配的番剧</p>
            </div>
        </div>
    </main>
    
    <footer class="footer">
        <div class="container">
            <p>数据更新时间: <span id="update-time"></span></p>
            <p>© 2025 B站追番列表 | 使用 Python 爬虫获取</p>
        </div>
        <button id="back-to-top" title="回到顶部"><i class="fas fa-arrow-up"></i></button>
    </footer>

    <script>
        // 将更新时间传递给JavaScript
        const updateTime = "''' + update_time + '''";
    </script>
    <script src="js/main.js"></script>
</body>
</html>'''
        
        # 写入HTML文件
        with open(self.html_file, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        print(f"HTML页面已生成: {self.html_file}")
        return True
    
    def generate_css(self):
        """生成CSS样式文件"""
        css_content = '''/* B站风格全局样式 */
:root {
    --bili-pink: #FB7299;          /* B站主色调粉色 */
    --bili-blue: #00A1D6;          /* B站蓝色 */
    --bili-orange: #FF9500;        /* B站橙色 */
    --bili-green: #2ECC71;         /* B站绿色 */
    --bili-bg: #F4F4F4;            /* 背景色 */
    --bili-card-bg: #FFFFFF;       /* 卡片背景 */
    --bili-text: #333333;          /* 主要文字 */
    --bili-text-light: #666666;    /* 次要文字 */
    --bili-border: #E5E5E5;       /* 边框颜色 */
    --bili-radius: 4px;            /* 圆角大小 */
    --bili-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    --bili-hover-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    --bili-transition: all 0.2s ease;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: "Helvetica Neue", Arial, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
    background-color: var(--bg-color);
    color: var(--text-color);
    line-height: 1.6;
}

.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 15px;
}

/* B站风格头部 */
.header {
    background: linear-gradient(135deg, var(--bili-pink) 0%, #FF6699 100%);
    color: white;
    padding: 12px 0;
    position: sticky;
    top: 0;
    z-index: 1000;
    box-shadow: 0 2px 8px rgba(251, 114, 153, 0.3);
}

.header .container {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.logo {
    display: flex;
    align-items: center;
    gap: 8px;
}

.logo i {
    font-size: 24px;
    color: white;
}

.logo h1 {
    font-size: 18px;
    font-weight: 600;
    margin: 0;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.search-box {
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 16px;
    padding: 6px 12px;
    width: 240px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.search-box input {
    border: none;
    background: transparent;
    padding: 4px 8px;
    flex-grow: 1;
    outline: none;
    color: white;
    font-size: 14px;
}

.search-box input::placeholder {
    color: rgba(255, 255, 255, 0.7);
}

.search-box button {
    background: transparent;
    border: none;
    color: white;
    cursor: pointer;
    padding: 4px;
}

.search-box button:hover {
    color: var(--bili-blue);
}

/* B站风格筛选区域 */
.filter-container {
    background: white;
    border-bottom: 1px solid var(--bili-border);
    padding: 16px 0;
    margin-bottom: 24px;
}

.filter-container .container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
}

.filter-tabs {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.filter-btn {
    background: none;
    border: 1px solid var(--bili-border);
    padding: 6px 16px;
    border-radius: var(--bili-radius);
    cursor: pointer;
    font-size: 14px;
    color: var(--bili-text-light);
    transition: var(--bili-transition);
    display: flex;
    align-items: center;
    gap: 6px;
}

.filter-btn:hover {
    border-color: var(--bili-pink);
    color: var(--bili-pink);
}

.filter-btn.active {
    background: var(--bili-pink);
    border-color: var(--bili-pink);
    color: white;
}

.filter-btn .count {
    background: rgba(0, 0, 0, 0.06);
    padding: 2px 6px;
    border-radius: 10px;
    font-size: 12px;
    min-width: 20px;
    text-align: center;
}

.filter-btn.active .count {
    background: rgba(255, 255, 255, 0.3);
}

.sort-options select {
    padding: 6px 12px;
    border-radius: var(--bili-radius);
    border: 1px solid var(--bili-border);
    outline: none;
    cursor: pointer;
    font-size: 14px;
    color: var(--bili-text);
    background: white;
    min-width: 120px;
}

.sort-options select:focus {
    border-color: var(--bili-pink);
}

/* B站风格番剧网格 */
.bangumi-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
    margin-bottom: 32px;
}

/* B站风格番剧卡片 */
.bangumi-card {
    background: var(--bili-card-bg);
    border-radius: var(--bili-radius);
    overflow: hidden;
    box-shadow: var(--bili-shadow);
    transition: var(--bili-transition);
    position: relative;
    height: 100%;
    border: 1px solid var(--bili-border);
}

.bangumi-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--bili-hover-shadow);
    border-color: var(--bili-pink);
}

.card-cover {
    position: relative;
    overflow: hidden;
    padding-top: 56.25%; /* 16:9 比例 */
}

.card-cover img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
}

.bangumi-card:hover .card-cover img {
    transform: scale(1.08);
}

.status-badge {
    position: absolute;
    top: 8px;
    right: 8px;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
    color: white;
    display: flex;
    align-items: center;
    gap: 4px;
    backdrop-filter: blur(4px);
    background: rgba(0, 0, 0, 0.6);
}

.status-badge.watching {
    background: rgba(46, 204, 113, 0.9);
}

.status-badge.finished {
    background: rgba(0, 161, 214, 0.9);
}

.card-info {
    padding: 12px;
}

.bangumi-title {
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 8px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    height: 42px;
    line-height: 1.4;
    color: var(--bili-text);
}

.bangumi-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: var(--bili-text-light);
    font-size: 12px;
}

.score, .progress {
    display: flex;
    align-items: center;
    gap: 4px;
}

.score i {
    color: var(--bili-orange);
    font-size: 11px;
}

.progress i {
    color: var(--bili-blue);
    font-size: 11px;
}

/* B站风格卡片悬停效果 */
.card-hover {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(45deg, rgba(251, 114, 153, 0.9), rgba(0, 161, 214, 0.9));
    color: white;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 16px;
    opacity: 0;
    transition: opacity 0.3s ease;
    backdrop-filter: blur(4px);
}

.bangumi-card:hover .card-hover {
    opacity: 1;
}

.bangumi-desc {
    text-align: center;
    margin-bottom: 16px;
    font-size: 13px;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.5;
}

.watch-btn {
    background: white;
    color: var(--bili-pink);
    text-decoration: none;
    padding: 8px 20px;
    border-radius: 20px;
    display: flex;
    align-items: center;
    gap: 6px;
    transition: var(--bili-transition);
    font-weight: 600;
    font-size: 14px;
    border: 2px solid transparent;
}

.watch-btn:hover {
    background: var(--bili-pink);
    color: white;
    border-color: white;
}

/* 无结果样式 */
.no-results {
    text-align: center;
    padding: 50px 0;
    color: var(--light-text);
}

.no-results i {
    font-size: 48px;
    margin-bottom: 15px;
    color: var(--primary-color);
}

/* 页脚样式 */
.footer {
    background-color: #fff;
    padding: 20px 0;
    text-align: center;
    color: var(--light-text);
    margin-top: 30px;
    position: relative;
}

#back-to-top {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 40px;
    height: 40px;
    background-color: var(--primary-color);
    color: white;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: var(--shadow);
    opacity: 0;
    visibility: hidden;
    transition: var(--transition);
}

#back-to-top.visible {
    opacity: 1;
    visibility: visible;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .header .container {
        flex-direction: column;
        gap: 15px;
    }
    
    .search-box {
        width: 100%;
    }
    
    .filter-container .container {
        flex-direction: column;
        gap: 10px;
    }
    
    .filter-tabs {
        width: 100%;
        overflow-x: auto;
        padding-bottom: 5px;
    }
    
    .sort-options {
        width: 100%;
    }
    
    .sort-options select {
        width: 100%;
    }
    
    .bangumi-grid {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    }
}

@media (max-width: 480px) {
    .bangumi-grid {
        grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
        gap: 10px;
    }
    
    .card-info {
        padding: 10px;
    }
    
    .bangumi-title {
        font-size: 14px;
        height: 42px;
    }
    
    .bangumi-meta {
        font-size: 12px;
    }
}'''
        
        # 写入CSS文件
        with open(self.css_file, 'w', encoding='utf-8') as f:
            f.write(css_content)
        
        print(f"CSS样式文件已生成: {self.css_file}")
    
    def generate_js(self):
        """生成JavaScript文件"""
        js_content = '''// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 设置更新时间
    document.getElementById('update-time').textContent = updateTime;
    
    // 筛选功能
    const filterButtons = document.querySelectorAll('.filter-btn');
    const bangumiCards = document.querySelectorAll('.bangumi-card');
    const noResults = document.querySelector('.no-results');
    
    filterButtons.forEach(button => {
        button.addEventListener('click', () => {
            // 移除所有按钮的active类
            filterButtons.forEach(btn => btn.classList.remove('active'));
            // 给当前点击的按钮添加active类
            button.classList.add('active');
            
            const filter = button.getAttribute('data-filter');
            let visibleCount = 0;
            
            bangumiCards.forEach(card => {
                if (filter === 'all' || card.getAttribute('data-status') === filter) {
                    card.style.display = 'block';
                    visibleCount++;
                } else {
                    card.style.display = 'none';
                }
            });
            
            // 显示或隐藏"无结果"提示
            if (visibleCount === 0) {
                noResults.style.display = 'block';
            } else {
                noResults.style.display = 'none';
            }
        });
    });
    
    // 搜索功能
    const searchInput = document.getElementById('search-input');
    const searchBtn = document.getElementById('search-btn');
    
    function performSearch() {
        const searchTerm = searchInput.value.toLowerCase().trim();
        let visibleCount = 0;
        
        bangumiCards.forEach(card => {
            const title = card.getAttribute('data-title').toLowerCase();
            
            // 检查当前筛选条件
            const activeFilter = document.querySelector('.filter-btn.active').getAttribute('data-filter');
            const statusMatch = activeFilter === 'all' || card.getAttribute('data-status') === activeFilter;
            
            if (title.includes(searchTerm) && statusMatch) {
                card.style.display = 'block';
                visibleCount++;
            } else {
                card.style.display = 'none';
            }
        });
        
        // 显示或隐藏"无结果"提示
        if (visibleCount === 0) {
            noResults.style.display = 'block';
        } else {
            noResults.style.display = 'none';
        }
    }
    
    searchBtn.addEventListener('click', performSearch);
    searchInput.addEventListener('keyup', function(event) {
        if (event.key === 'Enter') {
            performSearch();
        }
    });
    
    // 排序功能
    const sortSelect = document.getElementById('sort-select');
    const bangumiContainer = document.getElementById('bangumi-container');
    
    sortSelect.addEventListener('change', function() {
        const sortValue = this.value;
        const cardsArray = Array.from(bangumiCards);
        
        cardsArray.sort((a, b) => {
            const titleA = a.getAttribute('data-title');
            const titleB = b.getAttribute('data-title');
            
            if (sortValue === 'title-asc') {
                return titleA.localeCompare(titleB, 'zh-CN');
            } else if (sortValue === 'title-desc') {
                return titleB.localeCompare(titleA, 'zh-CN');
            }
            
            // 默认排序 - 保持原顺序
            return 0;
        });
        
        // 重新添加排序后的卡片
        cardsArray.forEach(card => {
            bangumiContainer.appendChild(card);
        });
    });
    
    // 回到顶部按钮
    const backToTopButton = document.getElementById('back-to-top');
    
    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 300) {
            backToTopButton.classList.add('visible');
        } else {
            backToTopButton.classList.remove('visible');
        }
    });
    
    backToTopButton.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
});'''
        
        # 写入JavaScript文件
        with open(self.js_file, 'w', encoding='utf-8') as f:
            f.write(js_content)
        
        print(f"JavaScript文件已生成: {self.js_file}")
    
    def run(self):
        """运行HTML生成器"""
        # 加载数据
        bangumi_data = self.load_data()
        if not bangumi_data:
            return False
        
        # 创建目录结构
        self.create_directory_structure()
        
        # 生成HTML、CSS和JS文件
        self.generate_html(bangumi_data)
        self.generate_css()
        self.generate_js()
        
        print(f"\n生成完成! 请在浏览器中打开 {self.html_file} 查看结果")
        return True

if __name__ == "__main__":
    generator = BangumiHTMLGenerator()
    generator.run()